import {createSlice} from '@reduxjs/toolkit'
import axios from 'axios'

const foodsStore = createSlice({
  name: 'foods',
  initialState:{
    foodsList: [],
    activeIndex: 0,
    cartList:[]
  },
  reducers:{
    setFoodsList(state, action){
      state.foodsList = action.payload
    },
    changeActiveIndex(state, action){
      state.activeIndex = action.payload
    },
    addCart(state, action){
      const item = state.cartList.find(item => item.id === action.payload.id)
      if(item){
        item.count++
      }else{
        state.cartList.push({...action.payload, count: 1})
      }
    },
    increCount(state, action){
      const item = state.cartList.find(item => item.id === action.payload)
      item.count++
    },
    decreCount(state, action){
      const item = state.cartList.find(item => item.id === action.payload)
      item.count--
      if(item.count === 0){
        state.cartList = state.cartList.filter(item => item.id !== action.payload)
      }
    },
    clearCart(state){
      state.cartList = []
    }
  }
})
const {setFoodsList, changeActiveIndex, addCart, decreCount, increCount, clearCart} = foodsStore.actions

export default foodsStore.reducer
export {changeActiveIndex, addCart, increCount, decreCount, clearCart}

export const fetchFoodsList = () => {
  return async (dispatch) => {
    const res = await axios.get(' http://localhost:3004/takeaway')
    console.log(res.data.takeaway)
    dispatch(setFoodsList(res.data))
  }
}